package com.authentications.service;

import com.authentications.security.DefaultUserDetailsService;
import com.authentications.security.WebSecurityConfig;
import com.authentications.security.info.SecurityValue;
import com.authentications.security.password.DefaultUserPassword;
import com.authentications.security.password.UserPassword;
import com.authentications.utils.JwtSpringSecurityTokenUtils;
import com.authentications.utils.SpringContextUtils;
import com.authentications.strategy.OpenSpringSecurity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @ClassName SpringSecurityServiceAutoConfiguration
 * @Author xiezhuocai
 * @Description SpringSecurity jwt认证模式
 * @Date 2021/12/19 23:02
 */
@Configuration
@ConditionalOnWebApplication
@EnableWebSecurity
@EnableConfigurationProperties(SecurityValue.class)
@ConditionalOnBean({OpenSpringSecurity.class})
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true,jsr250Enabled = true)
public class SpringSecurityServiceAutoConfiguration {

    @Autowired
    private SecurityValue securityValue;

    @Autowired
    private JwtSpringSecurityTokenUtils tokenUtils;

    @Bean
    public SpringContextUtils springContextUtils() {
        return new SpringContextUtils();
    }

    @Bean
    public JwtSpringSecurityTokenUtils jwtSpringSecurityTokenUtils(){
        return new JwtSpringSecurityTokenUtils(securityValue);
    }

    @Bean
    @ConditionalOnMissingBean(WebSecurityConfigurerAdapter.class)
    public WebSecurityConfig webSecurityConfig() {
        return new WebSecurityConfig(tokenUtils);
    }

    //密码编码器
    @Bean
    public PasswordEncoder passwordEncoder(){
        //return NoOpPasswordEncoder.getInstance();//不加密
        return new BCryptPasswordEncoder(); //BCrypt加密
    }

    @Bean
    public DefaultUserDetailsService userDetailsService(){
        return new DefaultUserDetailsService();
    }

    @Bean
    @ConditionalOnMissingBean(UserPassword.class)
    public DefaultUserPassword userPassword(){
        return new DefaultUserPassword();
    }

}
